import axios from 'axios'
import { getToken, setToken, getErrMsg } from 'assets/js/tools/Cookies'
import qs from 'qs'
const baseUrl = "/apis/v1/app"; 
// POST传参序列化
axios.defaults.baseURL = baseUrl;

axios.interceptors.request.use(function (config) { 
    let token = getToken();
    if (token) {
        config.headers.Authorization = "Bearer "+ token;     
    }
    return config;
}, function (error) {});

const timeout = 3000000;


// 封装文件上传的头信息
const $http = axios.create({ 
    timeout: timeout,
    transformRequest: [function(data) {
        return qs.stringify(data)
    }],
    paramsSerializer: function(data) {
        return qs.stringify(data)
    }
})

//get请求
export function fetch(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: params }, { timeout: timeout })
        .then(response => {
            resolve(response.data)
        })
        .catch((error) => {
            reject(getErrMsg(error)); 
        })
    })
}

// post 
export function postData(url, data, loadflag) {
    return new Promise((resolve, reject) => {
        axios.post( url, qs.stringify(data), {
            timeout: timeout
        })
        .then(response => {
            resolve(response.data)
        })
        .catch((error) => {
            reject(getErrMsg(error)); 
        })
    })
}

export default {
	sendPost( url,params ) {
        return postData( url, params );
	},
    sendGet( url, params ){
        return fetch( url, params );
    },
    // 用来上传模型文件
    uploadModelFile( params ){
        return new Promise((resolve, reject) => {
            let formData = new FormData()
            formData.append( 'file', params.file )
            $http.post('/model/file/upload', formData, {
                method: 'post',
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded',
                  "Authorization" : "Bearer " + getToken()
                },
                transformRequest: [function(data) {
                    return data
                }]
            }).then((response) => {
                resolve(response.data)
            }).catch(function(err) {
                reject(getErrMsg(err));
            })
        })
    }
}


